import React, {useEffect, useRef, useState} from "react";
import axios from "axios";

import {Avatar, Card, Col, Drawer, List, Row} from 'antd';
import { EditOutlined, EllipsisOutlined, PieChartOutlined, BarChartOutlined } from '@ant-design/icons';

import * as Echarts  from 'echarts';
import _ from 'lodash';  // 用于处理数据格式

const { Meta } = Card;

export default function Home() {
    const [viewList, setViewList] = useState([]);
    const [starList, setStarList] = useState([]);

    const { username, region, role: {roleName} }= JSON.parse(localStorage.getItem('token'));

    useEffect(()=>{
        // 获取已发布的新闻：按浏览量从大到小排序，只返回前6条新闻
        // _sort=view按view字段排序 _order=desc从大到小排序(不写这个的话，默认是从小到大)  _limit=6只返回前6个数据
        axios.get('/api/news?publishState=1&_expand=category&_sort=view&_order=desc&_limit=6').then(response=>{
            // console.log(response.data);
            setViewList(response.data);
        });
    }, []);
    useEffect(()=>{
        // 获取已发布的新闻：按点赞数从大到小排序，只返回前6条新闻
        axios.get('/api/news?publishState=1&_expand=category&_sort=star&_order=desc&_limit=6').then(response=>{
            setStarList(response.data);
        });
    }, []);


    // 柱状图
    const barRef= useRef();
    const [allDataList, setAllDataList]= useState([]);
    const renderBarView= (obj)=>{
        const mCharts = Echarts.init(barRef.current)
        const option = {  // 指定图表的配置项和数据
            title: {
                text: '新闻分类图示'
            },
            tooltip: {},
            legend: {
                data: ['数量']
            },
            xAxis: {
                data: Object.keys(obj),
                axisLabel: {
                    rotate: "45",  // x轴上的标签旋转45度
                    interval: 0    // 设置为0，强制显示所有标签
                }
            },
            yAxis: {
                minInterval: 1
            },
            series: [{
                name: '数量',
                type: 'bar',
                data: Object.values(obj).map(item=>item.length)
            }]
        }
        mCharts.setOption(option);  // 使用刚指定的配置项和数据显示图表

        window.onresize = () => {
            mCharts.resize();  // 图表尺寸大小自适应
        }
    }
    useEffect(()=>{
        axios.get('/api/news?publishState=1&_expand=category').then(response=>{
            // console.log(response.data)
            // console.log(_.groupBy(response.data, item=>item.category.title));  // 将响应数据按分类标题进行分组
            renderBarView(_.groupBy(response.data, item=>item.category.title));
            setAllDataList(response.data);
        });

        // useEffect若返回一个函数，则当组件销毁时会自动调用该返回函数
        return ()=>{
            window.onresize= null;
        }
    }, [])


    // 饼状图
    const [visible, setVisible] = useState(false);
    const pieRef= useRef(null);
    const [pieChart, setPieChart] = useState(null);
    const renderPieView = (obj) => {
        let currentList= allDataList.filter(item=>item.author===username);
        let groupObj = _.groupBy(currentList,item=>item.category.title);
        let list = [];
        for(let key in groupObj){
            list.push({
                name: key,
                value: groupObj[key].length
            })
        }

        let myChart;
        if(!pieChart){  // 这样写可避免饼状图的多次初始化
            myChart = Echarts.init(pieRef.current);
            setPieChart(myChart);
        } else{
            myChart = pieChart;
        }

        let option = {
            title: {
                text: '当前用户新闻分类图示',
                // subtext: '纯属虚构',
                left: 'center'
            },
            tooltip: {
                trigger: 'item'
            },
            legend: {
                orient: 'vertical',
                left: 'left',
            },
            series: [{
                name: '发布数量',
                type: 'pie',
                radius: '50%',
                data: list,
                emphasis: {
                    itemStyle: {
                        shadowBlur: 10,
                        shadowOffsetX: 0,
                        shadowColor: 'rgba(0, 0, 0, 0.5)'
                    }
                }
            }]
        };
        myChart.setOption(option);
    }

    const showDrawer = async () => {
        await setVisible(true);
        renderPieView();
    };

    return (
        <div>
            <Row gutter={16}>
                <Col span={8}>
                    <Card title="用户最常浏览" bordered={true} extra={<BarChartOutlined />}>
                        <List size="small" dataSource={viewList}
                              renderItem={item => <List.Item><a href={`#/news-manage/preview/${item.id}`}>{item.title}</a></List.Item>}
                        />
                    </Card>
                </Col>
                <Col span={8}>
                    <Card title="用户点赞最多" bordered={true} extra={<BarChartOutlined />}>
                        <List size="small" dataSource={starList}
                            renderItem={item => <List.Item><a href={`#/news-manage/preview/${item.id}`}>{item.title}</a></List.Item>}
                        />
                    </Card>
                </Col>
                <Col span={8}>
                    <Card cover={ <img alt="example" src="/bear.png" /> }
                        actions={[
                            <PieChartOutlined key="show" onClick={showDrawer}/>,
                            <EditOutlined key="edit" />,
                            <EllipsisOutlined key="ellipsis" />,
                        ]}
                    >
                        <Meta avatar={<Avatar src="/avatar.jpg" />} title={username}
                            description={<div>
                                <b>{region==='' ? '全球' : region }</b>
                                <span style={{marginLeft: '10px'}}>{roleName}</span>
                            </div>}
                        />
                    </Card>
                </Col>
            </Row>


            <div ref={barRef} style={{width:'100%', height:'400px', "marginTop":'30px'}}>

            </div>

            <Drawer title="个人新闻分类" placement="right" closable={true} width="500"
                    visible={visible} onClose={()=>setVisible(false)}  >
                <div ref={pieRef} style={{width:'100%', height:'400px', "marginTop":'30px'}}>

                </div>
            </Drawer>

        </div>
    );
};
